<template>
    <div v-loading="pager.loading" class="flex flex-col h-full">
        <el-scrollbar>
            <div class="grid gap-4 4xl:grid-cols-6 2xl:grid-cols-5 xl:grid-cols-4 sm:grid-cols-3">
                <div
                    v-for="(item, index) in (pager.lists as SquareVideoResponse[])"
                    :key="index"
                    class="video-item"
                >
                    <!-- 视频 -->
                    <aspect-ratio
                        :src="item.video_url"
                        :ratio="[4, 3]"
                        type="video"
                    />

                    <!-- 描述 -->
                    <div class="w-full h-full p-[15px] box-border">
                        <div class="line-clamp-2 text-tx-regular">
                            {{ item.prompt || '-' }}
                        </div>
                    </div>

                    <!-- 操作 -->
                    <div class="flex justify-between px-[15px] pb-[20px]">
                        <div class="flex items-center">
                            <template v-if="configs.is_user">
                                <ElAvatar :size="26" :src="item?.user?.avatar" />
                                <span class="ml-1.5 text-xs text-tx-placeholder">
                                    {{ item.user?.nickname }}
                                </span>
                            </template>
                        </div>
                        <div class="flex items-center gap-3">
                            <el-tooltip
                                effect="dark"
                                content="喜欢"
                                placement="bottom"
                            >
                                <div>
                                    <icon
                                        v-if="!item.is_collect"
                                        class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                        name="el-icon-Star"
                                        size="20"
                                        color="#556477"
                                        @click.stop="handleCollect(item.code, item.is_collect)"
                                    />
                                    <icon
                                        v-else
                                        class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                        name="el-icon-StarFilled"
                                        size="20"
                                        color="#fd5656"
                                        @click.stop="handleCollect(item.code, item.is_collect)"
                                    />
                                </div>
                            </el-tooltip>
                            <el-tooltip
                                effect="dark"
                                content="下载"
                                placement="bottom"
                            >
                                <div @click.stop="handleDownload(item.video_url, item.prompt)">
                                    <Icon
                                        class="cursor-pointer dark:hover:bg-[rgba(255,255,255,0.05)] hover:bg-[rgba(0,0,0,0.05)] rounded-md p-1 box-content"
                                        name="el-icon-Download"
                                        size="24"
                                        color="#556477"
                                    />
                                </div>
                            </el-tooltip>
                        </div>
                    </div>
                </div>
            </div>

            <div v-if="pager.lists.length <= 0 && !firstLoading">
                <el-empty description="空空如也~" />
            </div>
        </el-scrollbar>

        <div
            v-if="pager.lists.length > 0 && !firstLoading"
            class="flex justify-center my-4"
        >
            <paging
                v-model="pager"
                layout="prev, pager, next"
                @change="queryLists"
            />
        </div>
    </div>
</template>

<script setup lang="ts">
import { watchDebounced } from '@vueuse/core'
import { popupEnum } from '~/enums/app'
import useAppStore from '~/stores/app'
import useUserStore from '~/stores/user'
import downloadUtil from '~/utils/download'
import squareApi from '~/api/square'
import videoApi from '~/api/apply/video'

const props = withDefaults(
    defineProps<{
        cateId?: number;
        keyword?: string;
        configs?: SquareSettingResponse;
    }>(),
    {
        cateId: 0,
        keyword: '',
        configs: {} as SquareSettingResponse | any
    }
)

const appStore = useAppStore()
const userStore = useUserStore()
const firstLoading = ref<boolean>(true)

// 查询参数
const queryParams = reactive({
    cate: props.cateId,
    keyword: props.keyword
})

// 分页查询
const { pager, queryLists, resetPaging } = usePaging({
    fetchFun: squareApi.video,
    params: queryParams
})

/**
 * 收藏记录
 *
 * @param {string} code
 * @param {boolean} status
 * @author zero
 */
const handleCollect = async (code: string, status: boolean) => {
    if (!userStore.isLogin) {
        return appStore.setPopup(popupEnum.LOGIN)
    }

    await videoApi.collect(code)
    await queryLists()
    if (status) {
        feedback.msgSuccess('取消成功')
    } else {
        feedback.msgSuccess('收藏成功')
    }
}

/**
 * 下载视频
 *
 * @param {string} url
 * @param {string} name
 * @author zero
 */
const handleDownload = async (url: string, name: string) => {
    try {
        if (!userStore.isLogin) {
            return appStore.setPopup(popupEnum.LOGIN)
        }

        const res = await $request.get(
            { url, responseType: 'blob', baseURL: '' },
            { isReturnDefaultResponse: true, apiPrefix: '' }
        )

        const blob = new Blob([res._data], {
            type: res.headers.get('Content-Type')
        })
        const link = window.URL.createObjectURL(blob)
        downloadUtil.file(link, name)
    } catch (error) {
        feedback.msgError('视频下载失败: ' + error)
    }
}


watch(
    () => props.cateId,
    async () => {
        queryParams.cate = props.cateId
        queryParams.keyword = props.keyword
        await queryLists()
        firstLoading.value = false
    },
    { immediate: true }
)

watchDebounced(
    () => props.keyword,
    async (value) => {
        queryParams.keyword = value
        await resetPaging()
    },
    {
        debounce: 500
    }
)
</script>

<style scoped lang="scss">
.video-item {
    position: relative;
    display: flex;
    flex-direction: column;
    width: 100%;
    overflow: hidden;
    cursor: pointer;
    background: var(--el-bg-color);
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 8px;
    &:hover {
        box-shadow: 0 6px 8px 0 rgb(28 31 35 / 12%);
    }
}
</style>
